document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('#question-form');
  const answerDiv = document.querySelector('#answer');
  const errorDiv = document.querySelector('#error');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    errorDiv.textContent = '';
    answerDiv.textContent = '思考中...';

    try {
      const response = await fetch('/api/ask', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          question: document.querySelector('#question').value,
          department: document.querySelector('#department').value
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.detail || '请求失败');
      }

      answerDiv.innerHTML = `<p>${data.answer}</p>`;
    } catch (error) {
      errorDiv.textContent = `错误：${error.message}`;
      answerDiv.textContent = '';
      console.error('API请求错误:', error);
    }
  });
});